$(function () {
    window.hotelConstant = {
        'cover': 1,
        'character': 2,
        'gallery': 3,
        'addpic':4
    };
    
    // 初始化封面信息
    ajaxRequest('/Home/BookSetting/cover', {
        hotel: window.currentHotel
    }, 'POST', function (data) {
        var imageUrl = data.data.coverImageUrl;
        if (imageUrl !== undefined && imageUrl.length > 0) {
            refreshCover(imageUrl);
        }
    }, function () {});
    

    $('#cover-panel .picuture-upload, #cover-panel .picture-re-upload').on('click', function (e) {
        $('#submitPicture').data('config', 'bookCover').data('type', window.hotelConstant.cover);
        $('#pictureSelector').trigger('click');
    });

    // 记录tabs选择
    $('#characterTabs .tabs-tab').on('tabSelected.ulite.tabs', function (e, relatedTarget) {
        var tab = $(e.target);
        var hash = tab.attr('href').split('#')[1];
        window.location.hash = hash;
    });

    if (window.location.hash !== '') {
        $('#characterTabs .tabs-tab[href="' + window.location.hash + '"]').addClass('is-active').siblings('.tabs-tab').removeClass('is-active');
        $(window.location.hash).addClass('is-active').siblings('.tabs-panel').removeClass('is-active');
    }

    // 初始化图册信息
    ajaxRequest('/Home/BookSetting/gallery', {
        hotel: window.currentHotel
    }, 'POST', function (data) {
        refreshGallery(data.data.gallery);
    }, function () {});

    $('#gallery-panel').on('click', '.picuture-upload', function (e) {
        $('#submitPicture').data('config', 'bookGallery').data('type', window.hotelConstant.gallery).removeData('value');
        $('#pictureSelector').trigger('click');
    });


    $('#gallery-panel').on('click', '.picture-remove', function (e) {
        e.preventDefault();
        e.stopPropagation();
        if (window.confirm(lang('delete'))) {
            var items = window.galleryItems.slice(0);
            items.splice($(this).parents('.picture-container').index(), 1);
            ajaxRequest('/Home/BookSetting/saveGallery', {
                hotel: window.currentHotel,
                url: items.join(','),
            }, 'POST', function (data) {
                refreshGallery(items);
            }, function (error) {
                if (typeof error.responseJSON == 'undefined') {
                    window.alert(lang('tip.system'));
                } else {
                    window.alert(error.responseJSON.info);
                }
            });

        }
    });

    $('#gallery-panel').on('click', '.picture-re-upload', function (e) {
        $('#submitPicture').data('config', 'bookGallery').data('type', window.hotelConstant.gallery).data('value', $(this).parents('.picture-container').index());
        $('#pictureSelector').trigger('click');
    });


    // 初始化个性图片信息
    ajaxRequest('/Home/BookSetting/special', {
        hotel: window.currentHotel
    }, 'POST', function (data) {
        $('#requestCharacterDesc').val(data.data.special);
        var template = $('#characterTag');
        var tagHTML = '';
        window.selectedTag = [];
        $.each(data.data.specialTag, function (key, tag) {
            var templateTmp = $(template.clone().html());
            templateTmp.find('.character-tag-info').html(tag.name);
            if (tag.isDefault === 1) {
                templateTmp.addClass('character-tag-system');
            }
            if (tag.enable === 0) {
                templateTmp.removeClass('character-tag-selected');
            } else {
                window.selectedTag.push(tag.name);
            }
            tagHTML += templateTmp.prop('outerHTML');
        });
        if (window.selectedTag.length < 3) {
            tagHTML += $('#characterTagInput').clone().html();
        }
        $('#character-container').html(tagHTML);
        //掌柜说
        var templateTreasurer = $($('#templateShopkeeper').clone().html());
        var treasurerHTML = '';
        var corverHTML = '';
        $.each(data.data.specialInfo, function (key, specialInfo) {
            templateTreasurer.find('.picture').attr({'style':'background-image: url("'+specialInfo.specialImageUrl+'")'}).css('background-size', '100%');
            templateTreasurer.attr('name',specialInfo.specialId);  
            templateTreasurer.attr('index',specialInfo.index);
            var textWord = templateTreasurer.find('.personality-description p');
            if(specialInfo.special != ''){
                textWord.removeClass(lang('tiplog'));
            }else{
                textWord.addClass(lang('tiplog'));
            }
            textWord.text(specialInfo.special); 
            if(specialInfo.isactive == 1){
                templateTreasurer.find('.shopkeeper-cover').addClass('hidden');
                templateTreasurer.find('.clear').addClass('hidden');
                templateTreasurer.find('.cover-image').removeClass('hidden');
                templateTreasurer.attr("isShopkeeper",true);
                corverHTML += templateTreasurer.prop('outerHTML');
            }else{
                templateTreasurer.find('.shopkeeper-cover').removeClass('hidden');
                templateTreasurer.find('.clear').removeClass('hidden');
                templateTreasurer.find('.cover-image').addClass('hidden');
                templateTreasurer.attr("isShopkeeper",false);
                treasurerHTML += templateTreasurer.prop('outerHTML');
            }        
            
        });
        $('#treasurerContainer').prepend(corverHTML); 
        $('#treasurerContainer').append(treasurerHTML);         
    }, function () {});
    $('#character-panel').on('click',' .picture-re-shopkeeper-upload', function (e) {
        $('#submitPicture').data('config', 'bookSpecial').data('type', window.hotelConstant.character).data('value', $(this).parents('.picture-container').attr('name'));
        $('#pictureSelector').trigger('click');  
    });

    var submitTags = function (tags, successCallback, errorCallback, submitBtn) {
        var params = {};
        params.hotel = window.currentHotel;
        params.tag = tags.join(',');
        ajaxRequest('/Home/BookSetting/saveSpecialTag', params, 'post', successCallback, errorCallback, submitBtn);
    };
    $('#character-panel').on('click', '#requestTagSubmit', function (e) {
        var submitBtn = $(this);
        var newTag = $('#requestNewTag').val().trim();
        if (newTag.length === 0) {
            tooltipWrong(submitBtn, lang('label.1'));
            return false;
        }
        if (newTag.length < 0 || newTag.length > 15) {
            tooltipWrong(submitBtn, lang('label.2'));
            return false;
        }

        var tags = window.selectedTag.slice(0);
        tags.push(newTag);
        submitTags(tags, function (data) {
            $('#requestNewTag').val('');
            var template = $('#characterTag');
            var templateTmp = $(template.clone().html());
            templateTmp.find('.character-tag-info').html(newTag);
            templateTmp.insertBefore($('#character-tag-form'));
            window.selectedTag.push(newTag);
            if (tags.length >= 3) {
                $('#character-tag-form').remove();
            }
        }, function (error, obj) {
            if (typeof error.responseJSON == 'undefined') {
                tooltipWrong(obj, lang('tip.system'));
            } else if (error.responseJSON.status == 203) {
                tooltipWrong(obj, error.responseJSON.info);
                window.setTimeout(dialogLogin(), 1500);
            } else {
                tooltipWrong(obj, error.responseJSON.info);
            }
        }, submitBtn);
    }).on('click', '.character-tag-remove', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var submitBtn = $(this);
        var tag = $(this).parents('.character-tag');
        var tagName = tag.find('.character-tag-info').html();
        var tags = window.selectedTag.slice(0);
        $.each(window.selectedTag, function (key, value) {
            if (value === tagName) {
                tags.splice(key, 1);
                return false;
            }
        });
        submitTags(tags, function (data) {
            window.selectedTag = tags;
            if (tag.hasClass('character-tag-system')) {
                tag.removeClass('character-tag-selected');
            } else {
                tag.remove();
            }
            if (window.selectedTag.length === 2) {
                $('#character-container').append($('#characterTagInput').clone().html());
            }
        }, function (error, obj) {
            if (typeof error.responseJSON == 'undefined') {
                tooltipWrong(obj, lang('tip.system'));
            } else if (error.responseJSON.status == 203) {
                tooltipWrong(obj, error.responseJSON.info);
                window.setTimeout(dialogLogin(), 1500);
            } else {
                tooltipWrong(obj, error.responseJSON.info);
            }
        }, submitBtn);
    }).on('click', '.character-tag-system', function (e) {
        e.preventDefault();
        e.stopPropagation();
        var submitBtn = $(this);
        if (submitBtn.hasClass('character-tag-selected')) {
            return false;
        }
        if (window.selectedTag.length >= 3) {
            tooltipWrong(submitBtn, lang('label.3'));
            return false;
        }
        var tag = submitBtn;
        var tagName = tag.find('.character-tag-info').text();
        var tags = window.selectedTag.slice(0);
        tags.push(tagName);
        submitTags(tags, function (data) {
            tag.addClass('character-tag-selected');
            window.selectedTag.push(tagName);
            if (window.selectedTag.length >= 3) {
                $('#character-tag-form').remove();
            }
        }, function (error, obj) {
            if (typeof error.responseJSON == 'undefined') {
                tooltipWrong(obj, lang('tip.system'));
            } else if (error.responseJSON.status == 203) {
                tooltipWrong(obj, error.responseJSON.info);
                window.setTimeout(dialogLogin(), 1500);
            } else {
                tooltipWrong(obj, error.responseJSON.info);
            }
        }, submitBtn);
    });
    var treasurerContainer = $('#treasurerContainer');
    $('#shopkeeperClone').click(function(){
        $('#submitPicture').data('config', 'bookSpecial').data('type', window.hotelConstant.addpic);
        $('#pictureSelector').trigger('click');
    });  
    //显示隐藏
    treasurerContainer.on('mouseleave','.picture-container',function(e){
        e.preventDefault();
        e.stopPropagation();        
        var submitBtn = $(this);
        submitBtn.find('.down_sign_container').removeClass('open');
        
    });
    //掌柜说-设为封面
    treasurerContainer.on('click','.shopkeeper-cover',function(e){
        e.preventDefault();
        e.stopPropagation();        
        var submitBtn = $(this);
        var setShopkeeper = submitBtn.closest('.picture-container');
        var siblingShopkeeper = setShopkeeper.siblings('.picture-container');
        var specialId = setShopkeeper.attr('name');
        var index = setShopkeeper.attr('index');
        ajaxRequest('/Home/BookSetting/saveManage', {
            "hotel": window.currentHotel,
            "specialId":specialId,
            "index":index,
        }, 'POST', function (data) {
            setShopkeeper.attr("isShopkeeper",true);
            siblingShopkeeper.attr("isShopkeeper",false);
            setShopkeeper.find('.shopkeeper-cover').addClass('hidden');
            siblingShopkeeper.find('.shopkeeper-cover').removeClass('hidden');
            setShopkeeper.find('.clear').addClass('hidden');
            siblingShopkeeper.find('.clear').removeClass('hidden');
            setShopkeeper.find('.cover-image').removeClass('hidden');
            siblingShopkeeper.find('.cover-image').addClass('hidden');
            var cloneShopkeeper = setShopkeeper.clone();
            var cloneFristShopkeeper = siblingShopkeeper.eq(0).clone();
            siblingShopkeeper.eq(0).remove();
            setShopkeeper.after(cloneFristShopkeeper);
            setShopkeeper.remove();
            treasurerContainer.prepend(cloneShopkeeper);
        }, function (error) {});  
    });
    //掌柜说修改说明
    treasurerContainer.on('click','.shopkeeper-Introduction',function(e){
        e.preventDefault(); 
        var submitBtnDesc = $(this);
        var changeDescribe = submitBtnDesc.closest('.picture-container');
        var describe = changeDescribe.find('.personality-description p').text();
        $('#requestCharacterDesc').val(describe);
        $('#requestCharacterSubmit').data('specialId',changeDescribe.attr('name'));
       
    });
    //掌柜说推送
    treasurerContainer.on('click','.shopkeeper-push',function(e){
        e.preventDefault(); 
        var submitBtn = $(this);
        var setShopkeeper = submitBtn.closest('.picture-container');
        var siblingShopkeeper = setShopkeeper.siblings('.picture-container');
        var specialId = setShopkeeper.attr('name');
        var specialId_arr = [];
        specialId_arr.push(specialId);
        ajaxRequest('/Home/NewsPush/pushManage', {
            "hotel": window.currentHotel,
            "specialId":specialId_arr,
        }, 'POST', function (data) {
            layer.msg(lang('successfullypush'), {icon: 1});
            setShopkeeper.attr("isShopkeeper",true);
            siblingShopkeeper.attr("isShopkeeper",false);
            setShopkeeper.find('.shopkeeper-cover').addClass('hidden');
            siblingShopkeeper.find('.shopkeeper-cover').removeClass('hidden');
            setShopkeeper.find('.clear').addClass('hidden');
            siblingShopkeeper.find('.clear').removeClass('hidden');
            setShopkeeper.find('.cover-image').removeClass('hidden');
            siblingShopkeeper.find('.cover-image').addClass('hidden');
            var cloneShopkeeper = setShopkeeper.clone();
            setShopkeeper.remove();
            treasurerContainer.prepend(cloneShopkeeper);  
            var picture_container = $('#treasurerContainer .picture-container');
            var indexs = [];
            for(var i=0;i<picture_container.length;i++){
                var specialId = {};
                specialId.specialId = picture_container.eq(i).attr('name');
                specialId.index = i+1;
                indexs.push(specialId);
            }  
            ajaxRequest('/Home/BookSetting/manageSortIndex', {
                hotel: window.currentHotel,
                indexs:indexs,
            }, 'POST', function (data) {}, function (error) {});                
        }, function (error) {
            modalAlert(error.responseJSON.info);   
        });
    });    
    $('#requestCharacterSubmit').on('click', function (e) {
        e.preventDefault();
        e.stopPropagation();  
        var submitBtn = $(this); 
        var desc = $('#requestCharacterDesc').val();  
        if (desc.length === 0) {
            formInlineTip(submitBtn, lang('character.2'));
            return false;
        }          
        var params = {};
        params.hotel = window.currentHotel;
        params.special = desc;
        params.specialId = submitBtn.data('specialId');
        ajaxRequest('/Home/BookSetting/saveSpecialText', params, 'post', function (data) {
            var newDescribe = data.data.special;
            var newSpecialId = data.data.specialId;
            var pictureContainer = treasurerContainer.find('.picture-container');
            for(var i=0;i<pictureContainer.length;i++){
                var isChang = pictureContainer.eq(i).attr("name");
                var thatContainer = pictureContainer.eq(i).find('.personality-description p');
                if(parseInt(isChang) == parseInt(newSpecialId)){
                    thatContainer.html(newDescribe); 
                    if(thatContainer.text() != ''){
                        thatContainer.removeClass(lang('tiplog'));
                    }else{
                        thatContainer.addClass(lang('tiplog'));
                    }
                    break;
                }                 
            }   
            formInlineTip(submitBtn, lang('successfullySave'), 2);
            $('#shopkeeperChangeDescModal').modal('hide');
        }, null, submitBtn);
    });    
    //删除掌柜说
    treasurerContainer.on('click','.clear',function(){
        var submitBtn = $(this);
        var removeContainer = submitBtn.closest('.picture-container');
        var index = removeContainer.attr('name');
        var shopkeeperSay = removeContainer.find('.shopkeeper-cover');
        var isShopkeeper = removeContainer.attr("isShopkeeper");
        if(isShopkeeper == 'true'){
            window.alert(lang('Shopkeepe')); 
        }else{
            ajaxRequest('/Home/BookSetting/deleteSpecialInfo', {
                hotel: window.currentHotel,
                "specialId":index,
            }, 'POST', function (data) {
                removeContainer.remove();
            }, function (error) {
            });             
        }
    });
    //掌柜说排序
    $('#edit-shopkeeper').on('click',function(){
        $('.show-the-cover').addClass('hidden');
        $('.hide-the-cover').removeClass('hidden');
        $('#treasurerContainer').addClass('hidden');
        $('#newTreasureContainer').removeClass('hidden'); 
        $('#character-container').addClass('hidden');
        $('#character-container').prev('.content-panel').addClass('hidden');
        ajaxRequest('/Home/BookSetting/special', {
            hotel: window.currentHotel
        }, 'POST', function (data) {
            $('#newTreasureContainer').html('');
            var templateTreasurer = $($('#templateNewShopkeeper').clone().html());
            var treasurerHTML = '';
            $.each(data.data.specialInfo, function (key, specialInfo) {
                templateTreasurer.find('.picture').attr({'style':'background-image: url("'+specialInfo.specialImageUrl+'")'}).css('background-size', '100%');
                templateTreasurer.attr('name',specialInfo.specialId);     
                var textWord = templateTreasurer.find('.personality-description p');
                if(specialInfo.special != ''){
                    textWord.removeClass(lang('tiplog'));
                }else{
                    textWord.addClass(lang('tiplog'));
                }
                textWord.text(specialInfo.special); 
                if(specialInfo.isactive == 1){
                    templateTreasurer.attr("isShopkeeper",true);
                }else{
                    templateTreasurer.attr("isShopkeeper",false);
                    treasurerHTML += templateTreasurer.prop('outerHTML');
                }        
                
            });
            $('#newTreasureContainer').append(treasurerHTML).sortable({
                revert: true, 
                cursor: 'pointer'
            }).disableSelection();
        }, function () {});      
    });
    $("#characterTabs .tabs-tab:nth-child(1),#characterTabs .tabs-tab:nth-child(2)").click(function(){
        $(".cancelShopkeeper").trigger("click");   
    });
    $('.cancelShopkeeper').on('click',function(){
        $('.show-the-cover').removeClass('hidden');
        $('.hide-the-cover').addClass('hidden');
        $('#treasurerContainer').removeClass('hidden');
        $('#newTreasureContainer').addClass('hidden');
        $('#character-container').removeClass('hidden');
        $('#character-container').prev('.content-panel').removeClass('hidden');
    });
    $('.sureShopkeeper').on('click',function(){
        var picture_container = $('#newTreasureContainer .picture-container');
        var indexs = [];
        for(var i=0;i<picture_container.length;i++){
            var specialId = {};
            specialId.specialId = picture_container.eq(i).attr('name');
            specialId.index = i+1;
            indexs.push(specialId);
        }
        ajaxRequest('/Home/BookSetting/manageSortIndex', {
            hotel: window.currentHotel,
            indexs:indexs,
        }, 'POST', function (data) {
            $('.show-the-cover').removeClass('hidden');
            $('.hide-the-cover').addClass('hidden');
            $('#treasurerContainer').removeClass('hidden');
            $('#newTreasureContainer').addClass('hidden');
            $('#character-container').removeClass('hidden');
            $('#character-container').prev('.content-panel').removeClass('hidden');
                ajaxRequest('/Home/BookSetting/special', {
                    hotel: window.currentHotel
                }, 'POST', function (data) {
                    $('#treasurerContainer').html('');
                    var templateTreasurer = $($('#templateShopkeeper').clone().html());
                    var treasurerHTML = '';
                    var corverHTML = '';
                    $.each(data.data.specialInfo, function (key, specialInfo) {
                        templateTreasurer.find('.picture').attr({'style':'background-image: url("'+specialInfo.specialImageUrl+'")'}).css('background-size', '100%');
                        templateTreasurer.attr('name',specialInfo.specialId);  
                        templateTreasurer.attr('index',specialInfo.index);
                        var textWord = templateTreasurer.find('.personality-description p');
                        if(specialInfo.special != ''){
                            textWord.removeClass(lang('tiplog'));
                        }else{
                            textWord.addClass(lang('tiplog'));
                        }
                        textWord.text(specialInfo.special); 
                        if(specialInfo.isactive == 1){
                            templateTreasurer.find('.shopkeeper-cover').addClass('hidden');
                            templateTreasurer.find('.clear').addClass('hidden');
                            templateTreasurer.find('.cover-image').removeClass('hidden');
                            templateTreasurer.attr("isShopkeeper",true);
                            corverHTML += templateTreasurer.prop('outerHTML');
                        }else{
                            templateTreasurer.find('.shopkeeper-cover').removeClass('hidden');
                            templateTreasurer.find('.clear').removeClass('hidden');
                            templateTreasurer.find('.cover-image').addClass('hidden');
                            templateTreasurer.attr("isShopkeeper",false);
                            treasurerHTML += templateTreasurer.prop('outerHTML');
                        }        
                        
                    });
                    $('#treasurerContainer').prepend(corverHTML); 
                    $('#treasurerContainer').append(treasurerHTML);         
                }, function () {});            
        }, function () {});    
    });    
});
var refreshCover = function (url) {
    var cover = $('#cover-panel').find('.picture');
    cover.css('background-image', 'url(' + url + ')').css('background-size', '100%').removeClass('hidden');
};
var refreshCharacter = function (url,id) {
    var treasurerContainer = $('#treasurerContainer');
    var pictureContainer = treasurerContainer.find('.picture-container');
    for(var i=0;i<pictureContainer.length;i++){
        var specialId = pictureContainer.eq(i).attr('name');
        if(specialId == id){
            pictureContainer.eq(i).find('.picture').css('background-image', 'url(' + url + ')').removeClass('hidden');
            return;
        }
    }
};
var newCharacter = function (url,id,isactive,sortindex) {                
    var templateShopkeeper = $($('#templateShopkeeper').clone().html());
    templateShopkeeper.attr({'name':id});
    templateShopkeeper.attr({'index':sortindex});
    templateShopkeeper.find('.picture').css('background-image', 'url(' + url + ')').removeClass('hidden');
    if(isactive == 1){
        templateShopkeeper.find('.shopkeeper-cover').addClass('hidden');
        templateShopkeeper.find('.clear').addClass('hidden');
        templateShopkeeper.find('.cover-image').removeClass('hidden');
        templateShopkeeper.attr("isShopkeeper",true);
    }         
    var shopkeeperHTML = templateShopkeeper.prop('outerHTML');
    $('#treasurerContainer').append(shopkeeperHTML);
};
var refreshGallery = function (gallery) {
    window.galleryItems = gallery;
    var templatePicture = $('#templatePicture');
    var galleryHTML = '';
    $.each(gallery, function (key, value) {
        var template = $(templatePicture.clone().html());
        template.find('.picture').removeClass('hidden').css('background-image', 'url(' + value + ')').css('background-size', '100%');
        galleryHTML += template.prop('outerHTML');
    });
    if (gallery.length < 4) {
        galleryHTML += templatePicture.clone().html();
    }
    $('#gallery-container').html(galleryHTML);  
};

/* exported pictureCropperSuccess */
var pictureCropperSuccess = function (imageUrl, imageType) {
    var submitPicture = $('#submitPicture');
    switch (imageType) {
        case window.hotelConstant.cover:
            ajaxRequest('/Home/BookSetting/saveCoverImg', {
                hotel: window.currentHotel,
                url: imageUrl,
            }, 'POST', function (data) {
                refreshCover(imageUrl);
                $('#pictureModal').modal('hide');
            }, null, submitPicture);
            break;
        case window.hotelConstant.character:
            var index = submitPicture.data('value');
            ajaxRequest('/Home/BookSetting/saveSpecialImage', {
                hotel: window.currentHotel,
                specialId:index,
                specialImageUrl: imageUrl,
            }, 'POST', function (data) {
                refreshCharacter(imageUrl,index);
                $('#pictureModal').modal('hide');
            }, null, submitPicture);
            break;
        case window.hotelConstant.gallery:
            var index = submitPicture.data('value');
            var items = window.galleryItems.slice(0);
            if (index !== undefined) {
                items.splice(index, 1, imageUrl);
            } else {
                items.push(imageUrl);
            }
            ajaxRequest('/Home/BookSetting/saveGallery', {
                hotel: window.currentHotel,
                url: items.join(','),
            }, 'POST', function (data) {
                refreshGallery(items);
                $('#pictureModal').modal('hide');
            }, null, submitPicture);
            break;
        case window.hotelConstant.addpic:           
            var prarm = {};
            prarm.hotel = window.currentHotel;
            prarm.specialImageUrl = imageUrl;  
            ajaxRequest('/Home/BookSetting/addSpecialInfo', prarm, 'POST', function (data) {
                var id = data.data.specialId;
                var imageUrl = data.data.specialImageUrl;
                var isactive = data.data.isactive;
                var sortindex = data.data.sortindex;
                newCharacter(imageUrl,id,isactive,sortindex);       
            }, null, submitPicture);
            $('#pictureModal').modal('hide');
            break;
        default:
            break;
    }
};
